using System;
using System.Net.Mail;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;
using Microsoft.SharePoint;

namespace CKS.EBE.WebControls
{
    public class ContactForm : BaseForm
    {
        protected string MessageVal { get { return TextBoxValue("idMessage"); } }
        protected string SubjectVal { get { return TextBoxValue("idSubject"); } }

        protected override void OnSubmit(object sender, EventArgs e)
        {
            try
            {
                Debug.Write("Submitting contact form");

                string sEmail = BlogContext.Current.Settings.ContactEmail;

                if (!string.IsNullOrEmpty(sEmail))
                {
                    using (var site = new SPSite(Web.Url))
                    {
                        string sBody = "From: {0} ({1})" + Environment.NewLine + "Body:" + Environment.NewLine + "{2}";

                        SPWebApplication webApp = site.WebApplication;
                        MailMessage msg = new MailMessage(webApp.OutboundMailSenderAddress, sEmail, String.Format("{0} ({1})", SubjectVal, Web.Title), String.Format(sBody, NameVal, EmailVal, MessageVal));
                        msg.ReplyTo = new MailAddress(EmailVal);

                        SmtpClient smtp = new SmtpClient(webApp.OutboundMailServiceInstance.Server.Name);
                        smtp.Send(msg);
                    }
                }

                ResponseControl.Visible = true;
                FormControl.Visible = false;
            }
            catch (Exception ex)
            {
                ErrorLabel = ex.Message;
                Debug.WriteLine(ex);
            }
        }
    }
}
